//
//  IponeViewController.m
//  zuixin
//
//  Created by QJY on 14-8-18.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
//

#import "IponeViewController.h"
#import "Header.h"
#import "ChineseInclude.h"
#import "PinYinForObjc.h"
#import "DingSh.h"
#import "AppDelegate.h"
#import "DSCallViewController.h"
#import "FMDBManager.h"
#import "NSString+FirstLetter.h"
#import "pinyin.h"
#import "ChineseString.h"
#import "MBProgressHUD.h"
@interface IponeViewController()

@end

@implementation IponeViewController
{
    NSString *_st;
    UITableView *_tabView;
    NSMutableArray *_tellArray;
    NSString *_ce;
    NSString *_cs;
    NSMutableArray *_arty;
    NSMutableArray *searchResults;
    NSMutableArray *_sdt;
    NSArray *_dcg;
    NSArray *_scg;
    NSString *_hui;
    ABAddressBookRef addressBook;
    NSMutableArray *addressBookTemp;
    NSString *_nameString;
    DingSh * _addressBook;
    CFArrayRef allPeople;
    FMDBManager* _manager;
    MBProgressHUD *pro;
    NSUserDefaults *users;
    UIImageView *_views;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _dataArray =[[NSMutableArray alloc]init];
        _tellArray =[[NSMutableArray alloc]init];
        _indexArray =[[NSMutableArray alloc]init];
        _dcg =[[NSArray alloc]init];
        _views =[[UIImageView alloc]init];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self virds];
}
-(void)virds
{
    if(IOS7)
    {
        self.automaticallyAdjustsScrollViewInsets =NO;
        // 不透明的操作栏<br
        self.extendedLayoutIncludesOpaqueBars =NO;
        //视图控制器，四条边不指定
        self.edgesForExtendedLayout =UIRectEdgeNone;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        
    }
    self.title=@"联系人";
    [searchResults removeAllObjects];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    search.text =nil;
}
//添加通讯录的操作
-(void)readAllPeoples
{
    ABAddressBookRef addressBooks = nil;
    
    if ([[ UIDevice currentDevice ].systemVersion floatValue ]>= 6.0 ) {
        addressBooks = ABAddressBookCreateWithOptions ( NULL , NULL );
        dispatch_semaphore_t sema = dispatch_semaphore_create ( 0 );
        
        ABAddressBookRequestAccessWithCompletion (addressBooks, ^( bool granted, CFErrorRef error){ dispatch_semaphore_signal (sema);});
        dispatch_semaphore_wait (sema, DISPATCH_TIME_FOREVER );
    }else
    {
        addressBooks = ABAddressBookCreate ();
    }
    // 获取通讯录中的所有人
    allPeople = ABAddressBookCopyArrayOfAllPeople (addressBooks);
    // 通讯录中人数
    CFIndex nPeople = ABAddressBookGetPersonCount (addressBooks);
    
    for ( NSInteger i = 0 ; i<nPeople; i++)
    {
        _addressBook = [[ DingSh alloc ] init ];
        // 获取个人
        ABRecordRef person = CFArrayGetValueAtIndex (allPeople, i);
        CFTypeRef abName = ABRecordCopyValue (person, kABPersonAddressProperty );
        
        CFTypeRef abLastName = ABRecordCopyValue (person, kABPersonLastNameProperty );
        
        CFStringRef abFullName = ABRecordCopyCompositeName (person);
        
        _nameString = ( __bridge NSString *)abName;
        
        NSString *lastNameString = ( __bridge NSString *)abLastName;
        
        if (( __bridge id )abFullName != nil ) {
            
            _nameString = ( __bridge NSString *)abFullName;
            
        } else {
            if (( __bridge id )abLastName != nil )
            {
                _nameString = [ NSString stringWithFormat : @"%@ %@" , _nameString, lastNameString];
            }
        }
        _addressBook. name = _nameString;
        _addressBook. recordID = ( int ) ABRecordGetRecordID (person);;
        
        ABPropertyID multiProperties[] = {
            
            kABPersonPhoneProperty ,
            
            kABPersonEmailProperty
            
        };
        NSInteger multiPropertiesTotal = sizeof (multiProperties) / sizeof ( ABPropertyID );
        for ( NSInteger j = 0 ; j < multiPropertiesTotal; j++) {
            ABPropertyID property = multiProperties[j];
            
            ABMultiValueRef valuesRef = ABRecordCopyValue (person, property);
            
            NSInteger valuesCount = 0 ;
            
            if (valuesRef != nil ) valuesCount = ABMultiValueGetCount (valuesRef);
            
            if (valuesCount == 0 ) {
                
                CFRelease (valuesRef);
                
                continue ;
            }
            // 获取电话号码和 email
            ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
            for (int k = 0; k<ABMultiValueGetCount(phone); k++)
            {
                //获取电话Label
                NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
                NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
                _addressBook.tel =personPhone;
                NSLog(@"%@",personPhone);
                
                NSString *texe=[NSString stringWithFormat:@"%@:%@\n",personPhoneLabel,personPhone];
                               if([texe hasPrefix:@"移动"]||[texe hasPrefix:@"手机"]||[texe hasPrefix:@"移动手机"]||[texe hasPrefix:@"电话"])
                {
                    NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    _addressBook.mobile =df;
                }
                if([texe hasPrefix:@"工作传真"]||[texe hasPrefix:@"工作"])
                {NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    
                    _addressBook.work =df;
                }
                if( [texe hasPrefix:@"住宅传真"]||[texe hasPrefix:@"iPhone"])
                {
                    
                    NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    
                    _addressBook.other =df;
                }
                if([texe hasPrefix:@"其他"]||[texe hasPrefix:@"传呼"])
                {
                    NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    _addressBook.home =df;
                    NSLog(@"%@",texe);
                }
                if([texe hasPrefix:@"主要"]||[texe hasPrefix:@"住宅"])
                {
                    if([texe hasPrefix:@"主要"])
                    {
                    NSArray *lisd =[texe componentsSeparatedByString:@":"];
                    NSString *df =[lisd objectAtIndex:1];
                    _addressBook.main =df;
                    }
                    else
                    {
                        NSArray *lisd =[texe componentsSeparatedByString:@":"];
                        NSString *df =[lisd objectAtIndex:1];
                        _addressBook.main =df;
                    }}
            }
            CFRelease(person);
        }
        FMDBManager* manager = [FMDBManager sharedManager];
        [manager addUser:_addressBook];
    }
}
-(void)match

{
    
    pro = [[MBProgressHUD alloc] initWithView:self.view];
    
    pro.labelText = @"请稍后..";
    
    pro.mode = MBProgressHUDModeText;
    
    [self.view addSubview:pro];
    
    [pro showAnimated:YES whileExecutingBlock:^{
        
        [self  readAllPeoples];
        
    } completionBlock:^{
        
        [self nssary];
    }];
}

-(void)sleep
{
    UIButton*button=(UIButton*)[self.view viewWithTag:20];
    [button setUserInteractionEnabled:YES];
}
-(void)btnClickkk:(UIButton*)sender
{
    [sender setUserInteractionEnabled:NO];
    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(sleep) userInfo:nil repeats:NO];
    FMDBManager* manager = [FMDBManager sharedManager];
    [manager removeAllUsers];
    [self match];
    
    
    //[self readAllPeoples];
    [self virds];
    
}
-(void)searf
{
    //添加搜索栏
    search =[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    search.delegate =self;
    [search setPlaceholder:@"按名字首字母查询"];
    searchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:search contentsController:self];
    searchDisplayController.active = NO;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
    [self.view addSubview:search];
}
-(void)nssary
{
    _sdt =[[NSMutableArray alloc]init];
    UIButton*btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 20, 54, 44);
    [btn setTitle:@"刷新" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClickkk:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*bbj=[[UIBarButtonItem alloc]initWithCustomView:btn];
    bbj.tag=20;
    
    self.navigationItem.leftBarButtonItem=bbj;
    if(_dataArray.count>0)
    {
        _manager = [FMDBManager sharedManager];
        NSMutableArray *dscx =[NSMutableArray array];
        dscx = [_manager getAllUsers];
        if(dscx.count!=_dataArray.count)
        {
            [_dataArray removeAllObjects];
            _dataArray=dscx;
        }if(dscx.count==_dataArray.count)
        {
            NSLog(@"最新");
        }
        [_tabView reloadData];
    }
    else
    {
        _manager = [FMDBManager sharedManager];
        _dataArray = [_manager getAllUsers];
        [_tabView reloadData];
    }
    for(int i=0;i<[_dataArray count];i++)
    {
        NSString *fgy =((DingSh *)[_dataArray objectAtIndex:i]).name;
        [_sdt addObject:fgy];
        for(int i=0;i<[_sdt count];i++)
        {
            if ([[_sdt objectAtIndex:i] hasPrefix:@"ABMultiValueR"]) {
                [_sdt removeObject:[_sdt objectAtIndex:i]];
            }
        }
    }
    [_indexArray addObject:[ChineseString IndexArray:_sdt]];
    NSString *dgh =[_indexArray objectAtIndex:[_indexArray count]-1];
    NSString *string_2 = [(NSArray *)dgh componentsJoinedByString:@","];
    _scg =[string_2 componentsSeparatedByString:@","];
    _LetterResultArr = [ChineseString LetterSortArray:_sdt];
    [pro removeFromSuperview];
}
- (void)viewDidLoad
{
    //[[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    [super viewDidLoad];
    [search removeFromSuperview];
    [self searf];
    [self nssary];
   
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navgationbar.png"] forBarMetrics: UIBarMetricsDefault];
    
    NSDictionary *navTitleArr = [NSDictionary dictionaryWithObjectsAndKeys:
                                 //title字体－title字体颜色
                                 [UIFont boldSystemFontOfSize:23],UITextAttributeFont,
                                 [UIColor whiteColor],UITextAttributeTextColor ,nil];
    [self.navigationController.navigationBar setTitleTextAttributes:navTitleArr];
    //[self drawRect:CGRectMake(0, 0,320, 47
    // )];
    _tabView =[[UITableView alloc]initWithFrame:CGRectMake(0, 44, 320, DeviceHeight-64-49-search.frame.size.height) style:UITableViewStylePlain];
    _tabView.delegate =self;
    _tabView.dataSource =self;
    _tabView.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:_tabView];
    [_tabView reloadData];
}
- (UIImage *)barBackground
{
    //    /return [UIImage imageNamed:@"2.png"];
    return nil;
}

- (void)didMoveToSuperview
{
    //iOS5 only
    if ([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [self.navigationController.navigationBar setBackgroundImage:[self barBackground] forBarMetrics:UIBarMetricsDefault];
    }
}

//this doesn't work on iOS5 but is needed for iOS4 and earlier
- (void)drawRect:(CGRect)rect
{
    //draw image
    [[self barBackground] drawInRect:rect];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    for(int i=0;i<[_indexArray count];i++)
    {
        _dcg =[_indexArray objectAtIndex:i];
    }
    return _dcg;
}
#pragma mark - Section header view
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 10)];
    //lab.backgroundColor =[UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1];
    lab.text = [_scg objectAtIndex:section];
    //lab.textColor = [UIColor whiteColor];
    //lab.font=[UIFont fontWithName:@"Courier-Bold" size:22];
    return lab;;
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.0;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return 1;
    }
    else{
        return [_scg count];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return searchResults.count;
    }
    else
    {
        if(_LetterResultArr.count==0)
        {
            return 0;
        }
        else
        {
            return [[_LetterResultArr objectAtIndex:section] count];
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor =[UIColor clearColor];
        UIImageView *imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tab_contacts.png"]];
        imageView.frame =CGRectMake(0, 17, 30, 30);
        [cell addSubview:imageView];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text =nil;
    cell.selectionStyle =UITableViewCellSelectionStyleGray;
    cell.textLabel.textColor =[UIColor blackColor];
    cell.textLabel.font= [UIFont fontWithName:@"Arial Rounded MT Bold" size:16];
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        cell.textLabel.text =[NSString stringWithFormat:@"      %@",[searchResults objectAtIndex:indexPath.row]];
    }
    else
    {
        cell.textLabel.text =[NSString stringWithFormat:@"     %@",[[_LetterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DSCallViewController *call =[[DSCallViewController alloc]init];
    if(searchResults.count>0)
    {
        _ce =[searchResults objectAtIndex:indexPath.row];
        for(int i=0;i<[_dataArray count];i++)
        {
            NSString *name =((DingSh *)[_dataArray objectAtIndex:i]).name;
            NSString *mains =((DingSh *)[_dataArray objectAtIndex:i]).main;
            NSString *mobbi =((DingSh *)[_dataArray objectAtIndex:i]).mobile;
            NSString *homer =((DingSh *)[_dataArray objectAtIndex:i]).home;
            NSString *workd =((DingSh *)[_dataArray objectAtIndex:i]).work;
            NSString *other =((DingSh *)[_dataArray objectAtIndex:i]).other;
            NSString *teld =((DingSh *)[_dataArray objectAtIndex:i]).tel;
            NSMutableArray *cey =[[NSMutableArray alloc]initWithObjects:name,mains,mobbi,homer,workd,other,teld, nil];
            if([_ce isEqualToString:[cey objectAtIndex:0]])
            {
               _cs=[NSString stringWithFormat:@"   %@   %@   %@   %@   %@   %@",[cey objectAtIndex:0],[cey objectAtIndex:3],[cey objectAtIndex:4],[cey objectAtIndex:5],[cey objectAtIndex:2],[cey objectAtIndex:1]];
                NSString* cs1=[NSString stringWithFormat:@"%@%@%@%@%@%@",[cey objectAtIndex:0],[cey objectAtIndex:3],[cey objectAtIndex:4],[cey objectAtIndex:5],[cey objectAtIndex:1],[cey objectAtIndex:2]];
                
                if ([cs1 isEqualToString:[NSString stringWithFormat:@"%@",[cey objectAtIndex:0]]])
                {
                    _cs=[NSString stringWithFormat:@"   %@   %@",[cey objectAtIndex:0],teld];
                    
                }

            }
        }
        call.array =_cs;
    }
    else
    {
        _st =[NSString stringWithFormat:@"     %@",[[_LetterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
        for(int i=0;i<[_dataArray count];i++)
        {
            NSString *name =((DingSh *)[_dataArray objectAtIndex:i]).name;
           
            NSString *mains =((DingSh *)[_dataArray objectAtIndex:i]).main;
            NSString *mobbi =((DingSh *)[_dataArray objectAtIndex:i]).mobile;
            NSString *homer =((DingSh *)[_dataArray objectAtIndex:i]).home;
            NSString *workd =((DingSh *)[_dataArray objectAtIndex:i]).work;
            NSString *other =((DingSh *)[_dataArray objectAtIndex:i]).other;
            NSString *teld =((DingSh *)[_dataArray objectAtIndex:i]).tel;
            NSMutableArray *cey =[[NSMutableArray alloc]initWithObjects:name,mobbi,mains,homer,workd,other,teld, nil];
            NSString *res=[_st stringByReplacingCharactersInRange:NSMakeRange(0, 5) withString:@""];
            if([res isEqualToString:[cey objectAtIndex:0]])
            {
                _cs=[NSString stringWithFormat:@"   %@   %@   %@   %@   %@   %@",[cey objectAtIndex:0],[cey objectAtIndex:3],[cey objectAtIndex:4],[cey objectAtIndex:5],[cey objectAtIndex:1],[cey objectAtIndex:2]];
                NSString* cs1=[NSString stringWithFormat:@"%@%@%@%@%@%@",[cey objectAtIndex:0],[cey objectAtIndex:3],[cey objectAtIndex:4],[cey objectAtIndex:5],[cey objectAtIndex:1],[cey objectAtIndex:2]];
                
                if ([cs1 isEqualToString:[NSString stringWithFormat:@"%@",[cey objectAtIndex:0]]])
                {
                    _cs=[NSString stringWithFormat:@"   %@   %@",[cey objectAtIndex:0],teld];
                    
                }

            }
        }
        call.array =_cs;
    }
    UINavigationController *nvc =[[UINavigationController alloc]initWithRootViewController:call];
    [self presentViewController:nvc animated:YES completion:^{
    }];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchResults removeAllObjects];
    [searchBar resignFirstResponder];
    [_tabView reloadData];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{searchResults = [[NSMutableArray alloc]init];
    if (search.text.length>0&&![ChineseInclude isIncludeChineseInString:search.text])
    {
        for (int i=0; i<[_dataArray count]; i++)
        {
            if ([ChineseInclude isIncludeChineseInString:((DingSh *)[_dataArray objectAtIndex:i]).name])
            {
                NSString *fvd =[NSString stringWithFormat:@"%s",[[search.text firstLetter] UTF8String]];
                NSString *fgv =[fvd uppercaseString];
                NSRange titleResult=[((DingSh *)[_dataArray objectAtIndex:i]).name rangeOfString:fgv];
                if (titleResult.length>0)
                {
                    [searchResults addObject:((DingSh *)[_dataArray objectAtIndex:i]).name];
                }
                NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:((DingSh *)[_dataArray objectAtIndex:i]).name];
                NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:search.text options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0)
                {
                    [searchResults addObject:((DingSh *)[_dataArray objectAtIndex:i]).name];
                }
            }
            else {
                NSRange titleResult=[((DingSh *)[_dataArray objectAtIndex:i]).name rangeOfString:search.text options:NSCaseInsensitiveSearch];
                if (titleResult.length>0)
                {
                    [searchResults addObject:((DingSh *)[_dataArray objectAtIndex:i]).name];
                    NSLog(@"====777==%@",searchResults);
                    [_tabView reloadData];
                }
                [_tabView reloadData];
            }
        }
    }
    if (search.text.length>0&&[ChineseInclude isIncludeChineseInString:search.text])
    {
        for(int j=0;j<[_dataArray count];j++)
        {
            NSRange titleResult=[((DingSh *)[_dataArray objectAtIndex:j]).name rangeOfString:search.text];
            if (titleResult.length>0)
            {
                [searchResults addObject:((DingSh *)[_dataArray objectAtIndex:j]).name];
            }
        }
    }
    [_tabView reloadData];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end

